package com.xp.flower.qsd.utils.weixin;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xp.flower.qsd.task.WeChatTask;
import com.xp.flower.qsd.utils.HttpUtils;

public class WeiXinUtils {
    
    private static final Logger logger = LoggerFactory.getLogger(WeChatTask.class);
    
    public static final String encodeURL(String str){
        try{
          return URLEncoder.encode(str, "utf-8"); 
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
          logger.error("url加密错误");
        }
        return str;
    }
    

    /** 获取微信登录需要用的code ***/
    public static JSONObject getWeiXinLoginAccessTokenByCode(String code){
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token";  
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("appid", WeiXinGlobalConstants.getProperties("appid"));
        params.put("secret", WeiXinGlobalConstants.getProperties("secret"));
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        String result = null;
        try {
            result = HttpUtils.sendGet(url, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.parseObject(result);
    }
    
    //验证access_token是否有效
    //由于access_token有效期比较短，当access_token失效后，可以使用refresh_token进行刷新，
    //refresh_token的有效期为30天。refresh_token失效后需要用户重新授权。
    public static JSONObject validateWeiXinAccessToken(String accessToken,String openid){
        String isOkAccessTokenURL= "https://api.weixin.qq.com/sns/auth";
        HashMap<String,String> tokenIsOkParams = new HashMap<String,String>();
        tokenIsOkParams.put("ACCESS_TOKEN", accessToken);
        tokenIsOkParams.put("OPENID", openid);
        String isOKAccessTokenresult = null;
        try {
            isOKAccessTokenresult = HttpUtils.sendGet(isOkAccessTokenURL, tokenIsOkParams);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.parseObject(isOKAccessTokenresult);
    }
    
    /**
     * 说明：
     * @return
     * @author 获取用户信息
     * @time：2017年7月5日 下午2:22:23
     */
    public static JSONObject getWeiXinUserInfo(String accessToken,String openid){
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo";
        HashMap<String,String> userInfoParams = new HashMap<String,String>();
        userInfoParams.put("access_token", accessToken);
        userInfoParams.put("openid", openid);
        userInfoParams.put("lang", "zh_CN");
        String userInfoResult = null;
        try {
            userInfoResult = HttpUtils.sendGet(userInfoUrl, userInfoParams);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.parseObject(userInfoResult);
    }

}
